<template>
  <div class="selector-container">
    <el-select
        v-model="selectedValue"
        :multiple="isMultiple"
        :placeholder="isMultiple ? '请选择多个选项' : '请选择一个选项'"
        @change="handleChange"
        clearable
    >
      <el-option
          v-for="option in options"
          :key="option.value"
          :label="option.label"
          :value="option.value"
      />
    </el-select>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ElSelect, ElOption } from 'element-plus';

// 定义选项数据类型
interface Option {
  label: string;
  value: string | number;
}

// 定义组件入参
const props = defineProps<{
  options: Option[];
  multiple?: boolean;
}>();

// 定义组件出参
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | number | (string | number)[] | undefined): void;
}>();

// 处理选择逻辑
const selectedValue = ref<string | number | (string | number)[] | undefined>(undefined);

// 监听选择变化并触发事件
const handleChange = (value: string | number | (string | number)[]) => {
  emit('update:modelValue', value);
};

// 监听外部值的变化
watch(
    () => props.options,
    (newOptions) => {
      // 当选项数据变化时，如果当前选中值不在新选项中，则清空
      if (selectedValue.value !== undefined) {
        if (props.multiple && Array.isArray(selectedValue.value)) {
          const validValues = newOptions.map(option => option.value);
          const newValue = selectedValue.value.filter(v => validValues.includes(v));
          if (newValue.length !== selectedValue.value.length) {
            selectedValue.value = newValue;
            emit('update:modelValue', newValue);
          }
        } else if (!props.multiple && !newOptions.some(option => option.value === selectedValue.value)) {
          selectedValue.value = undefined;
          emit('update:modelValue', undefined);
        }
      }
    },
    { deep: true }
);
</script>

<style scoped>
.selector-container {
  width: 100%;
  max-width: 300px;
}
</style>
